package com.itfreer.data.syn.base;

import java.util.Date;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.itfreer.data.syn.DataSynConfigService;
import com.itfreer.data.syn.DataSynService;
import com.itfreer.data.syn.entity.DataSynEntity;
import com.itfreer.form.api.DataOptionService;
import com.itfreer.utils.json.JsonUtils;

/**
 * 定义数据同步下的数据操作
 */
@Component
public class DataSynOptionService implements DataOptionService {

	@Autowired
	private DataSynConfigService dataSynConfigService;
	@Autowired
	private DataSynService dataSynService;

	@Override
	public void add(String table, Object entity) {
		if (dataSynConfigService.hasTable(table)) {
			DataSynEntity synEntity = new DataSynEntity();
			synEntity.setId(UUID.randomUUID().toString().replace("-", ""));
			synEntity.setTable(table);
			synEntity.setData(JsonUtils.toJSONString(entity));
			synEntity.setType("add");
			synEntity.setAddDate(new Date());
			synEntity.setAll(false);
			synEntity.setFailTimes(0);
			dataSynService.add(synEntity);
		}
	}

	@Override
	public void delete(String table, String dataid) {
		if (dataSynConfigService.hasTable(table)) {
			DataSynEntity synEntity = new DataSynEntity();
			synEntity.setId(UUID.randomUUID().toString().replace("-", ""));
			synEntity.setTable(table);
			synEntity.setData(dataid);
			synEntity.setType("delete");
			synEntity.setAddDate(new Date());
			synEntity.setAll(false);
			synEntity.setFailTimes(0);
			dataSynService.add(synEntity);
		}
	}

	@Override
	public void update(String table, Object entity) {
		if (dataSynConfigService.hasTable(table)) {
			DataSynEntity synEntity = new DataSynEntity();
			synEntity.setId(UUID.randomUUID().toString().replace("-", ""));
			synEntity.setTable(table);
			synEntity.setData(JsonUtils.toJSONString(entity));
			synEntity.setType("update");
			synEntity.setAddDate(new Date());
			synEntity.setAll(false);
			synEntity.setFailTimes(0);
			dataSynService.add(synEntity);
		}
	}
}
